import React from 'react';
import {StatusBar, StyleSheet, TextInput, View,} from 'react-native';
import * as Color from "../../../lib.xjs/constant/Color";
import RippleButton from "../../../lib.xjs/widget/btn/RippleButton";
import TouchButton from "../../../lib.xjs/widget/btn/HighlightButton";
import HttpHelper from "../../../lib.xjs/helper/HttpHelper";
import {UUID} from "../../../lib.xjs/util/UUID";
import SmsHelper from "../../../lib.xjs/helper/SmsHelper";
import * as BizConstant from "../../constant/BizContant";
import StorageUtil from "../../../lib.xjs/util/StorageUtil";
import {NavigationActions} from 'react-navigation'
import {NumberUtil} from "../../../lib.xjs/util/NumberUtil";
import BizUser from "../../entity/BizUser";

import Global from './../../../gaqu/Global';
import * as ToastAndroid from "react-native/Libraries/Components/ToastAndroid/ToastAndroid.android";
import L from "../../../lib.xjs/util/L";

/** 登录 */
export default class GaquLogin extends React.Component {

    static navigationOptions = ({ navigation }) => ({
        title: '登录',
        // header: null,
    });

    mSmsHelper:SmsHelper;
    /** 输入验证码 */
    code:String = "";

    constructor(props){
        super(props);
        this.state=({
            textBtnSms: '获取',
            /** 输入手机号 */
            mobile : "",
        });
        // this.mSmsHelper = SmsHelper.getInstance();   // 单例
        this.mSmsHelper = new SmsHelper();
    }

    render() {
        return (
            <View style={styles.container}>
                <StatusBar
                    // hidden={true}
                    // translucent={true}
                    backgroundColor={Color.colorPrimaryDark} />

                <TextInput
                    style={styles.label_value}
                    underlineColorAndroid={'transparent'}
                    value={this.state.mobile}
                    onChangeText={(text) => {
                        this.setState({
                            mobile : NumberUtil.getFormatPhone(text),
                        });
                    }}
                    maxLength={13}
                    keyboardType="numeric"
                    placeholder={'手机号'} />

                <View
                    style={styles.label_value_right}>
                    <TextInput
                        style={styles.right_1}
                        underlineColorAndroid={'transparent'}
                        placeholder={'验证码'}
                        onChangeText={(text) => {
                            this.code = text;
                        }}
                        maxLength={4}
                        keyboardType="numeric"/>

                    <RippleButton styleText={styles.right_2} title={this.state.textBtnSms} onPress={()=>{this._sendSms()}}/>

                </View>

                <View style={styles.line_layout}>
                    <TouchButton styleTouch={styles.buttonTouch}
                                 underlayColor={Color.colorPrimaryDark}
                                 styleText={styles.buttonText}
                                 title={'提交'}
                                 onPress={()=>{ this._onSubmit() }}/>
                </View>

                <HttpHelper ref={'http'}/>
            </View>
        );
    }


    /** 发送验证码回调 */
    _smsCallback = (text:string) => {
        if(!text) return;
        this.setState({
            textBtnSms:text,
        });
    };

    /** 发送验证码 */
    _sendSms():void{
        this.mSmsHelper.start(this._smsCallback, this.state.mobile);
    }

    /** 注册/登录 */
    _onSubmit():void{
        if(!this.refs.http) return;
        if(!this.state.mobile){
            ToastAndroid.show("请输入手机号码", ToastAndroid.SHORT);
            return;
        }

        let mobile = this.state.mobile.replace(/ /g, "");
        if(!NumberUtil.isPhoneNumber(mobile)){
            ToastAndroid.show("手机号码有误", ToastAndroid.SHORT);
            return;
        }

        if(!this.code || !NumberUtil.is4Digtal(this.code)){
            ToastAndroid.show("验证码有误", ToastAndroid.SHORT);
            return;
        }

        let head = new Map();
        head.set("Content-Type", "application/json");

        let map = new Map();
        map.set("mobile", mobile);
        map.set("code", this.code);

        this.refs.http.setURL(BizConstant.POST_VERIFY_LOGIN)
            .setMethod(HttpHelper.POST)
            .setNotiInfo("正在登录")
            .setHeadParams(head)
            .setBodyParams(map)
            .setRequestId(UUID.getOne())
            .setListener((responseCode:number, res:Object) => {
                if(responseCode !== HttpHelper.RESPONSE_SUCCESS) return;
                // L.logOnly("responseCode:" + responseCode + ", res:" + res);
                this._gotoLogin(res);
            })
            .setTimeout(10 * 1000)
            .start(true);
    }

    _gotoLogin(res:Object):void{

        // 存储手机号+token
        BizUser.token = res.data.token;
        let obj = {
            "mobile": this.state.mobile.replace(/ /g, ""),
            "token": res.data.token,
        };
        StorageUtil.getInstance().doSave("history", obj);
        L.logOnly("存储的token:" + res.data.token);

        // 初始化全局变量
        let bizUser     = res.data.user;
        bizUser.token   = res.data.token;
        bizUser.roles   = res.data.roles;
        global.bizUser  = bizUser;

        // 清空栈跳转
        let resetAction = NavigationActions.reset({
            index: 0,
            actions: [
                NavigationActions.navigate({routeName:"RoleSelect"})//要跳转到的页面名字
            ]
        });
        this.props.navigation.dispatch(resetAction);
    }

}

const styles = StyleSheet.create({
    container: {
        flexDirection:'column',
        flex:1,
        // alignItems: 'center',
        // justifyContent: 'center',
        paddingLeft:25,
        paddingRight:25,
    },
    label_value: {
        height: 50,
        // width:100,
        color:Color.black,
        borderRadius:4,
        borderWidth:1,
        borderColor:Color.gray,
        marginBottom:10,
        marginTop:30,
        paddingLeft: 10,
        paddingRight: 10,
    },
    label_value_right: {
        flexDirection: 'row',
        justifyContent: 'flex-end',
        alignItems:'center',
        height: 50,
        // width:100,
        borderRadius:4,
        borderWidth:1,
        borderColor:Color.gray,
        marginBottom:10,
        marginTop:10,
        paddingRight:5,
    },
    right_1: {
        flex:1,
        height: 50,
        paddingLeft: 10,
        paddingRight: 10,
        // width:100,
    },
    right_2: {
        // width:100,
        fontSize: 16,
        color:Color.colorPrimaryLight,
    },
    line_layout: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        paddingTop:5,
        paddingBottom:5,
    },
    buttonTouch: {
        flex:1,
        height: 50,
        backgroundColor:Color.colorPrimary,
    },
    buttonText: {
        fontSize: 22,
        color:Color.white,
    },
});


